package ru.tairov.rtsedd.service;

import java.util.ArrayList;
import java.util.List;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.tairov.rtsedd.model.MyEntity;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

@Service
public class EntityService {

	private static final Logger logger = LoggerFactory
			.getLogger(EntityService.class);

	@Autowired
	private DB db;

	public MyEntity findEntity(String id) {

		// Uncomment when you have defined your entity
		//
		if ("new".equals(id)) {
			return new MyEntity();
		} else {
			// return em.find(MyEntity.class, id);

			DBCollection coll = db.getCollection("test");

			DBObject searchById = new BasicDBObject("_id", new ObjectId(id));
			DBObject found = coll.findOne(searchById);

			return new MyEntity(id, (String) found.get("name"));
		}
	}

	public MyEntity save(MyEntity entity) {

		DBCollection coll = db.getCollection("test");
		
		DBObject obj = new BasicDBObject();
		
		obj.put("name", entity.getName());

		if (entity.getId() != null) {

			DBObject searchById = new BasicDBObject("_id", new ObjectId(entity.getId()));
			DBObject found = coll.findOne(searchById);
			
			coll.update(found, obj);
			
		} else {

			coll.save(obj);

			String idString = obj.get("_id").toString();

			entity.setId(idString);
		}

		logger.info("entity saved: ");
		return entity;

	}

	public boolean delete(String entityId) {

		return true;
	}

	public List<MyEntity> getAllEntities() {
		
		List<MyEntity> res = new ArrayList<MyEntity>();

		DBCollection coll = db.getCollection("test");
		
		DBCursor curs = coll.find();
		
		while(curs.hasNext()) {
			
			DBObject obj = curs.next();
			
			res.add(new MyEntity(obj.get("_id").toString(), obj.get("name").toString()));
		}
		
		return res;
	}

}
